//
//  TYZNetworkingTool.m
//  kanhujia
//
//  Created by lxl on 2018/5/14.
//  Copyright © 2018年 lxl. All rights reserved.
//

#import "TYZNetworkingTool.h"
#import <AFNetworking/AFNetworking.h>
#import <SystemConfiguration/CaptiveNetwork.h>
@implementation TYZNetworkingTool
+ (instancetype)initial {
    static dispatch_once_t onceToken;
    static TYZNetworkingTool *instance = nil;
    dispatch_once(&onceToken,^{
        instance = [[TYZNetworkingTool alloc] init];
        [instance setupManager];
    });
    return instance;
}
- (AFHTTPSessionManager *)manager {
    if (_manager == nil) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)setupManager {
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 告诉服务器请求参数类型
    [self.manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/css",@"image/gif",@"application/zip",@"application/x-tgz", nil]];
    // 设置超时时间
    [self.manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    self.manager.requestSerializer.timeoutInterval = 3.0;
    [self.manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
}
- (void)setupCookie {
    if (CoreInfo.session_id && CoreInfo.rememberMe) {
        CoreInfo.isLogined = YES;
        [self.manager.requestSerializer setValue:[NSString stringWithFormat:@"session.id=%@;rememberMe=%@", CoreInfo.session_id, CoreInfo.rememberMe] forHTTPHeaderField:@"Set-Cookie"];
    }
}
+ (void)post:(NSString *)port params:(NSDictionary *)params success:(void (^)(NSString *string, id data))success failure:(void (^)(NSString *error))failure {
    NSString *url = [Request_Prefix stringByAppendingString:port];
    [NetTool.manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (CoreInfo.isLogined == NO) {
            if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
                NSHTTPURLResponse *header = (NSHTTPURLResponse *)task.response;
                NSString *str = [header.allHeaderFields objectForKey:@"Set-Cookie"];
                NSArray *arr = [str componentsSeparatedByString:@";"];
                CoreInfo.session_id = [arr.firstObject componentsSeparatedByString:@"id="].lastObject;
                CoreInfo.rememberMe = [arr[5] componentsSeparatedByString:@"rememberMe="].lastObject;
                [NetTool setupCookie];
            }
        }
        [self successWithPort:port responseObject:responseObject success:success failure:failure];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self failureWithPort:port error:error failure:failure];
    }];
}
+ (void)successWithPort:(NSString *)port responseObject:(id)responseObject success:(void (^)(NSString *string, id data))success  failure:(void (^)(NSString *error))failure {
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
    NSNumber *code = [dict objectForKey:Request_Code];
    NSString *str = [dict objectForKey:Request_Message];
    id object = [dict objectForKey:Request_Data];
    if ([code isEqual:@(1)]) {
        if (success) {
            success(str, object);
        }
    } else {
        if (failure) {
            TYZLog(@"%@ %@", str, port);
            failure(str);
        }
    }
}
+ (void)failureWithPort:(NSString *)type error:(NSError *)error failure:(void (^)(NSString *error))failure {
    if (failure) {
        NSString *string = error.localizedDescription;
        if ([string hasPrefix:[@"请求超时" S]]) {
            string = @"连接失败，请重试";
        }
        TYZLog(@"%@ %@", string, type);
        failure(string);
    }
}
- (NetworkType)networkType {
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *subviews = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    for (id subview in subviews) {
        if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            int networkType = [[subview valueForKeyPath:@"dataNetworkType"] intValue];
            switch (networkType) {
                case 0:
                    return NetworkType_None;
                    break;
                case 1:
                    return NetworkType_2G;
                    break;
                case 2:
                    return NetworkType_3G;
                    break;
                case 3:
                    return NetworkType_4G;
                    break;
                case 5:
                {
                    int networkIntensity = [[subview valueForKeyPath:@"wifiStrengthRaw"] intValue];
                    if (networkIntensity > -70) {
                        self.networkIntensity = NetworkIntensity_High;
                    } else if (networkIntensity > -80) {
                        self.networkIntensity = NetworkIntensity_Mid;
                    } else {
                        self.networkIntensity = NetworkIntensity_Low;
                    }
                }
                    return NetworkType_Wifi;
                    break;
                default:
                    break;
            }
        }
    }
    return NetworkType_None;
}
- (void)getWifiInfo {
    id info = nil;
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        NSString *str1 = info[@"SSID"]; // 信号名称
        NSString *str2 = info[@"BSSID"];// 信号强度
        NSString *str3 = [[NSString alloc] initWithData:info[@"SSIDDATA"] encoding:NSUTF8StringEncoding];// 信号名称
        NSLog(@"%@ - %@ - %@", str1, str2, str3);
    }
}
@end
